﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SCABaselineCS.Tests.Security
{
    [TestClass]
    public class XmlInjectionTests
    {
        public void Snippet_Fail(string s)
        {
            var xmlSnippet = new StringBuilder();
            xmlSnippet.Append("<root>");
            xmlSnippet.Append("<item>" + s + "</item>");
            xmlSnippet.Append("</root>");
            var returnValue = System.Xml.Linq.XElement.Parse(xmlSnippet.ToString());
        }

        public void Snippet_Pass(int i)
        { // note: I'm not saying this is GOOD code, just that it's safe from injection
            var xmlSnippet = new StringBuilder();
            xmlSnippet.Append("<root>");
            xmlSnippet.Append("<item>" + i + "</item>");
            xmlSnippet.Append("</root>");
            var returnValue = System.Xml.Linq.XElement.Parse(xmlSnippet.ToString());
        }

        [TestMethod]
        public void Example_Fail()
        {
            // Arrange
            var maliciousString = "</item>";
            bool threwException = false;

            // Act
            Action a = () => { Snippet_Fail(maliciousString); };

            try { a.Invoke(); }
            catch { threwException = true; }

            // Assert
            Assert.IsTrue(threwException);
        }

        [TestMethod]
        public void Example_Pass()
        {
            // Arrange
            bool threwException = false;

            // Act
            Action attempt = () => {
                // boundary checks for Int32 parameter
                Snippet_Pass(Int32.MinValue);
                Snippet_Pass(-1);
                Snippet_Pass(0);
                Snippet_Pass(1);
                Snippet_Pass(Int32.MaxValue);
            };

            try { attempt.Invoke(); }
            catch { threwException = true; }

            // Assert
            Assert.IsFalse(threwException);
        }

    }
} // namespace